<template>
  <div>
    <el-card>
      <div class="flex flex-between flex-center">
        <div class="title">编辑产品</div>
      </div>
    </el-card>

    <el-container>

      <el-main>
        <el-card>
          <div slot="header ">产品卡片设置</div>
          <div class="flex flex-center justify-content">
            <!-- 左边部分 -->
            <div style="width:400px">
              <el-form
                :label-position="labelPosition"
                label-width="80px"
                :model="form"
              >
                <el-form-item label="产品标题:">

                  <el-input v-model="form.productTitle"></el-input>
                </el-form-item>
                <el-form-item label="产品详情:">
                  <el-input
                    type="textarea"
                    :rows="4"
                    placeholder="请输入内容"
                    v-model="form.productName"
                  >
                  </el-input>
                </el-form-item>
                <el-form-item label="产品分类:">
                  <div class="flex flex-between">
                    <el-input
                      v-model="curCategory"
                      style="width:320px"
                    ></el-input>
                    <div class="flex flex-center">
                      <img
                        src="../../../assets/image/add-icon2.png"
                        style="width:12px;height:12px;margin-right:5px"
                        alt=""
                      >
                      <div
                        class="add-category"
                        @click="addCategory"
                      >添加分类
                      </div>
                    </div>
                  </div>

                </el-form-item>
                <div class="flex ">
                  <div class="fontC">请选择分类:</div>
                  <div class="choose-category flex">
                    <div
                      class="fontA"
                      style="margin-left:30px;margin-bottom:10px;"
                      :class="curIndex === k ? 'active': ''"
                      @click="changeCategory(k)"
                      v-for="(v,k) in categoryList"
                      :key="k"
                    >
                      {{v.className}}
                    </div>
                  </div>

                </div>
                <el-form-item
                  label="上传文档:"
                  style="margin-top:30px"
                  
                >

                  <el-upload
                    class="el-input"
                    action="void"
                    accept=".pdf"
                    :http-request="customUpload"
                    :on-remove="handleRemove"
                    :on-progress="progressA"
                    :file-list="fileList"
                    ref="uploads"
                    :auto-upload="true"
                    :before-upload="beforePDFUpload"
                    :limit="1"
                    :on-exceed="exceed"
                    :show-file-list="false"
                  >
                    <div
                      v-loading="pdfLoading"
                      class="upload-btn  flex flex-center justify-content "
                      :class="form.productFileName ? 'uploaded flex-start' : ''"
                    >
                      <img
                        v-if="!form.productFileName"
                        src="../../../assets/image/upload-icon.png"
                        style="width:18px;height:17px;margin-right:10px"
                        alt=""
                      >
                      <div class="ellipsis" :class="form.productFileName ? ' fontB-bule' : 'fontC'">{{form.productFileName ? form.productFileName : '请点击上传PDF' }}</div>
                    </div>
                  </el-upload>

                </el-form-item>
              </el-form>
            </div>
            <!-- 右边部分 -->
            <div style="width:310px;height:460px;margin-left:121px;">
              <el-card body-style="padding:0px">
                <div style="position: relative;">
                  <img
                    class="cover"
                    @mouseenter="inCover"
                    :src="form.pdfHomePage"
                  ></img>
                  <!-- src="../../../assets/404_images/404.png" -->
                  <div
                    class="mask flex flex-center justify-content"
                    v-if="showMask"
                    @mouseleave="outCover"
                  >
                    <div
                      class="flex-one"
                      style="text-align:center"
                      @click="checkCover"
                    >
                      <img
                        class="icon"
                        src="../../../assets/image/checkCover.png"
                        alt=""
                      >
                      <p class="text">查看图片</p>
                    </div>

                    <div
                      class="flex-one "
                      style="text-align:center"
                      @click="changeCover"
                    >
                      <img
                        class="icon"
                        src="../../../assets/image/changeCover.png"
                        alt=""
                      >
                      <p class="text">更换图片</p>
                    </div>

                  </div>
                  <!-- 查看图片 -->
                  <el-dialog
                    :visible.sync="centerDialogVisible"
                    style="border-radius: 16px"
                    :before-close="handleClose"
                    class="myPicShowDialogClass"
                    center
                  >
                    <span>
                      <img
                        :src="form.pdfHomePage"
                        style="width:520px;height:520px"
                      >
                    </span>
                  </el-dialog>
                  <!-- 更换图片 -->
                  <el-dialog
                    class="myPicShowDialogClass"
                    :visible.sync="showUpload"
                    style="border-radius: 16px"
                    center
                  >
                    <el-card>
                      <div slot="header">上传图片</div>
                      <div class="flex flex-col flex-center">
                        <el-upload
                          class=""
                          action="void"
                          accept=".jpg,.jpeg"
                          :http-request="uploadImg"
                          :on-remove="handleRemove"
                          :on-progress="progressA"
                          :file-list="fileList"
                          ref="upload"
                          :before-upload="beforeImgUpload"
                          :auto-upload="true"
                          :limit="1"
                          :on-exceed="exceed"
                          :show-file-list="false"
                          v-loading="loading"
                        >
                          <div
                            
                            v-if="!imgUrl"
                            class="upload-pop-wrap"
                          >
                            <img
                              style="width:44px;height:44px;margin-top:113px"
                              src="../../../assets/image/add-icon.png"
                              alt=""
                            >
                            <div>添加图片</div>
                            <p>只支持JPG / PNG图片，大小不得超过5M,建议上传XXX*XXX的尺寸</p>
                          </div>
                          <img
                            v-if="imgUrl"
                            :src="imgUrl"
                            style="width: 360px;height: 360px;"
                            alt=""
                          >
                        </el-upload>
                      </div>

                      <div
                        class="flex flex-center flex-end"
                        style="padding:24px 0px;"
                      >
                        <img
                          style="width:18px;height:18px;margin-right:30px"
                          src="../../../assets/image/max-icon.png"
                          alt=""
                        >
                        <img
                          style="width:18px;height:18px;margin-right:30px"
                          src="../../../assets/image/min-icon.png"
                          alt=""
                        >
                        <img
                          style="width:20px;height:21.67px"
                          src="../../../assets/image/route-icon.png"
                          alt=""
                        >
                      </div>
                      <div
                        class="flex flex-between"
                        style="margin:0 80px; "
                      >
                        <el-button @click="showUpload = false"> 取消</el-button>
                        <el-button
                          type="primary"
                          @click="confirmImg"
                        >确定</el-button>
                      </div>
                    </el-card>
                  </el-dialog>
                </div>
                <div class="flex flex-col flex-center">
                  <div
                    class="product-title ellipsis"
                    :model="form.productTitle"
                  >{{form.productTitle}}</div>
                  <div
                    class="product-text"
                    :model="form.productName"
                  >{{form.productName}}</div>
                </div>
              </el-card>
            </div>
          </div>

        </el-card>
        <el-footer class="flex flex-between">

          <el-button
            type="danger"
            plain
            style="width:86px;height:40px;margin-top:30px;margin-left:82px;"
            @click="handleDelete"
            v-show="status == 1"
          >删除</el-button>
          <div class="flex-one"></div>
          <el-dialog
            :visible.sync="deletePop"
            style="border-radius: 16px"
            class="myPicShowDialogClasss"
            center
          >
            <div class="delete-pop-wrap">
              <div
                class="flex flex-center justify-content"
                style="width:280px;height:124px"
              >您是否要删除该产品?</div>
              <div
                style="padding:19px 42px;"
                class="border-top"
              >
                <el-button
                  style="width:88px;height:36px"
                  @click="deletePop = false"
                > 取消</el-button>
                <el-button
                  style="width:88px;height:36px"
                  type="primary"
                  @click="confirmDelete"
                >确定</el-button>
              </div>
            </div>
          </el-dialog>
          <div
            class="footer-btn-wrap flex flex-end"
            border
          >
            <el-button style="width: 160px;height: 40px;margin-right:72px;"
            @click="back"
            >取消</el-button>
            <el-button
              type="primary"
              style="width: 160px;height: 40px;"
              @click="commit"
            >提交</el-button>

          </div>
        </el-footer>
      </el-main>
    </el-container>
  </div>
</template>
<script>
import { getToken } from '@/utils/auth'
import {
  getProduct,
  getCategoryList,
  addProductCategory,
  deleteProduct,
  insertProduct,
  editProduct
} from '@/api/product.js'
import axios from 'axios'
import { setTimeout } from 'timers'

export default {
  data() {
    return {
      loading: false,
      limitNum: 1, // 上传excell时，同时允许上传的最大数
      deletePop: false,
      fileList: [], // excel文件列表
      centerDialogVisible: false, // 查看图片的弹层
      showUpload: false, // 更换图片的弹层
      showMask: false, // 展示遮罩层
      scale: 100,
      fileName: null, // 上传文件的名称
      labelPosition: 'top',
      curIndex: 0, // 当前选择的分类
      categoryList: [],
      isComplete: false, // 是否完成上传
      curCategory: null,
      productId: null,
      imgUrl: null, // 产品图片
      status: null, // 1.编辑产品    2.新增产品
      form: {},
      imgFile:null, // 图片文件
      pdfLoading: false,  // PDF loading 
      img: 'http://wximg.ycvod.cn/leftBack2.png',
      name: '图片测试',
      productClassId: null
    }
  },
  created() {
    this.productId = this.$route.query.id
    if (this.productId) {
      this.status = 1
      this.initData(this.productId)
    } else {
      this.form = this.$route.query.params
      this.status = 2
      getCategoryList({ pageNo: 1, pageSize: 10 }).then(res => {
        this.categoryList = res.data.datas
        console.log(this.categoryList, '...')
        this.curCategory = this.categoryList[this.curIndex].className
        this.form.productClassId = this.categoryList[
          this.curIndex
        ].productClassId
      })
    }
  },
  mounted() {
    // console.log('this.$route.query.id', this.$route.query.id)
    // context.drawImage()
  },

  methods: {
    // 弹窗中的上传
    uploadImg(file) {
      let FormDatas = new FormData()
      console.log(file)
      this.productFile = file.file.name
      FormDatas.append('file', file.file)
      this.isUpload = true
      this.loading = true
      axios({
        url: 'http://114.55.105.176:7005/productfile/upLoad',
        method: 'post',
        headers: {
          "Access-Token": getToken()
        },
        data: FormDatas,
        //上传进度
        onUploadProgress: progressEvent => {
          let num = ((progressEvent.loaded / progressEvent.total) * 100) | 0 //百分比
          file.onProgress({ percent: num }) //进度条
        }
      }).then(res => {
        this.loading = false
        this.imgFile = res.data.data
        this.imgUrl = 'http://114.55.105.176:7000/temp/' + this.imgFile.fileUrl
        this.isComplete = true
        this.$refs.upload.clearFiles();
        file.onSuccess() //上传成功(打钩的小图标)
      })
    },
    back(){
      this.$router.go(-1);//返回上一层
    },
    
    // 确认文件
    confirmImg() {
      this.showUpload = false
      this.form.pdfHomePage = this.imgUrl
      // this.form.productFileName = this.file.productFileName
      // this.form.productFile = {
      //   materialsIds:this.file.materialsIds,
      //   fileUrl: this.file.fileUrl
      // }
    },
    // 确认删除
    confirmDelete() {
      deleteProduct(this.productId).then(res => {
        this.deletePop = false
        this.$message({
          type: 'success',
          message: '已删除该产品'
        })
        this.$router.push('/product/list')
      })
    },
    // 编辑或新增
    commit() {
      if (this.status === 1) {
        // 编辑
        editProduct(this.form).then(res => {
          console.log()
          this.$message({
            message: '修改成功',
            type: 'success'
          })
          this.$router.push('/product/list')
        })
      } else if (this.status === 2) {
        // 新增
        this.form.productClassId = this.categoryList[
          this.curIndex
        ].productClassId
        insertProduct(this.form)
          .then(res => {
            this.$message({
              message: '新增成功',
              type: 'success'
            })
            this.$router.push('/product/list')
          })
          .catch(err => {
            this.$message.error('err')
          })
      }
    },

    // 获取产品数据
    initData(id, isLoading = true) {
      // 获取分类
      getCategoryList({ pageNo: 1, pageSize: 10 }).then(res => {
        this.categoryList = res.data.datas
        this.curCategory = this.categoryList[this.curIndex].className
        this.productClassId = this.categoryList[this.curIndex].productClassId
      })

      if (!isLoading) return
      // 获取产品详情
      if (this.status == 1) {
        getProduct(id).then(res => {
          this.$nextTick(() => {
            this.form = res.data
            if (this.productClassId) {
              this.form.productClassId = this.productClassId
            }
          })
          console.log(this.form)
        })
      }
    },
    onRemove(files, fileList) {
      this.fileList = []
    },
    // 校验图片文件
    beforeImgUpload(file) {
      const isImg = file.type === "image/jpeg"
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isImg) {
        this.$message.error('上传封面图片只能是 JPG/JPEG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传封面图片大小不能超过 2MB!')
      }
      return isImg && isLt2M
    },
    // 检验PDF文件
    beforePDFUpload(file) {
      const isPDF = file.type === 'application/pdf'
      const isLt100M = file.size / 1024 / 1024 < 100
      if (!isPDF) {
        this.$message.error('上传文件只能是 PDF 格式!')
      }
      if (!isLt100M) {
        this.$message.error('上传PDF大小不能超过 100MB!')
      }
      return isPDF && isLt100M
    },
    // 上传PDF
    customUpload(file) {
      let FormDatas = new FormData()
      console.log(file)
      this.productFile = file.file.name
      FormDatas.append('file', file.file)
      this.isUpload = true
      this.pdfLoading = true
      axios({
        url: 'http://114.55.105.176:7005/productfile/upLoadPDF',
        method: 'post',
        data: FormDatas,
        //上传进度
        
        onUploadProgress: progressEvent => {
          let num = ((progressEvent.loaded / progressEvent.total) * 100) | 0 //百分比
          file.onProgress({ percent: num }) //进度条
        }
      }).then(res => {
        this.pdfLoading = false
        this.file = res.data.data
        let newList = this.file.materialsIds.split(',')
        this.imgUrl = 'http://114.55.105.176:7000/temp/' + newList[0]
        this.isComplete = true
        // this.showUpload = false
        this.$refs.uploads.clearFiles();
        this.form.pdfHomePage = this.imgUrl
        this.form.productFileName = this.file.productFileName
        this.form.productFile = {
          materialsIds:this.file.materialsIds,
          fileUrl: this.file.fileUrl
        }
        file.onSuccess() //上传成功(打钩的小图标)
      })
    },
    /**     文件正在上传时的钩子    **/
    progressA(event, file) {
      this.percent = event.percent
    },
    exceed() {
      this.$message('不能上传更多')
    },
    /**     移除上传文件    **/
    handleRemove(file) {
      // this.$refs.upload.abort() //取消上传
      // this.imgUrl = ""
      // this.$message({ message: '成功移除' + file.name, type: 'success' })
    },
    // 切换图片
    changeCover() {
      this.showUpload = true
      this.loading = false
    },
    handleClose() {
      this.centerDialogVisible = false
    },
    // 查看封面图片
    checkCover() {
      this.centerDialogVisible = true
    },

    // 进入封面区域
    inCover(e) {
      this.showMask = true
    },
    // 离开封面区域
    outCover(e) {
      this.showMask = false
    },
    onSubmit() {
      console.log('submit!')
    },
    changeCategory(index) {
      this.curIndex = index
      this.curCategory = this.categoryList[this.curIndex].className
    },

    // 删除产品
    handleDelete() {
      this.deletePop = true
    },
    // 添加产品分类
    addCategory() {
      this.$prompt('添加分类', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(({ value }) => {
          console.log('成功', value)

          addProductCategory({ className: value, id: this.productId }).then(
            res => {
              this.initData(this.productId, false)
            }
          )
          this.$message({
            type: 'success',
            message: '已添加分类: ' + value
          })
        })
        .catch(() => {
          console.log('失败', value)
          this.$message({
            type: 'info',
            message: '取消输入'
          })
        })
    }
  }
}
</script>
<style lang="scss">
.active {
  padding: 0px 8px;
  border-radius: 4px;
  border: 1px solid #015dff;
  color: #015dff !important;
  margin-top: -1px;
}
.myPicShowDialogClass .el-dialog__header {
  padding: 0;
}

.myPicShowDialogClass .el-dialog__body {
  padding: 0;
}

.el-input {
  min-width: 136rpx;
}
.add-category {
  font-size: 12px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #015dff;
}
.choose-category {
  width: 300px;
  flex-wrap: wrap;
}
.upload-btn {
  width: 400px;
  height: 54px;
  background: #f9f9f9;
  border-radius: 4px;
  border: 1px dashed #d9d9d9;
}
.uploaded {
  padding-left: 14px;
}
.product-title {
  font-size: 18px;
  width: 280px;
  text-align: center;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #000000;
  margin-top: 39px;
}
.product-text {
  margin-top: 9px;
  width: 243px;
  height: 56px;
  font-size: 13px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #626262;
}
.cover {
  width: 310px;
  height: 310px;

  border-radius: 10px 10px 0px 0px;
}

.mask {
  position: absolute;
  background-color: rgba(0, 0, 0);
  opacity: 0.8;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 100;
}
.icon {
  width: 44px;
  height: 44px;
  opacity: 1 !important;
}
.icon:hover {
  padding: 2px;
  border-radius: 50%;
}
.text {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #ffffff;
}

.upload-pop-wrap {
  width: 360px;
  height: 360px;
  background: #f2f2f2;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
  img {
    margin-top: 118px;
  }
  div {
    margin-top: 20px;
    font-size: 18px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #015dff;
  }
  p {
    margin-top: 37px;
    width: 265px;
    height: 20px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #888888;
    text-align: center;
    line-height: 20px;
  }
}
.footer-btn-wrap {
  margin-top: 30px;
  margin-right: 82px;
}
.delete-pop-wrap {
  width: 280px;
  height: 200px;
}
.myPicShowDialogClass .el-dialog {
  width: 520px;
}
.myPicShowDialogClasss .el-dialog {
  width: 280px;
}
.myPicShowDialogClasss .el-dialog__header {
  padding: 0;
}

.myPicShowDialogClasss .el-dialog__body {
  padding: 0;
}
.border-top {
  border-top: 1px solid #e9e9e9;
}
</style>
